#!/bin/sh

GRUBMENU=/boot/grub/grub.conf.test

get_grub_default_kernel_partition()
{
    # Get default value
    local DEFAULT=$(grep -E "^[[:space:]]*default[[:space:]]*={0,1}" $GRUBMENU | sed -e 's/.*\([0-9]+\)/\1/')
echo $DEFAULT
    DEFAULT=$(expr $DEFAULT "+" 1)
    
    # get default entry
    local LB=$(grep -n "title" $GRUBMENU | awk -F ':' -v NUM=$DEFAULT '{ if (NR == NUM) {print $1}}')
    local NEXT_ENTRY=$(expr $DEFAULT "+" 1)
    local LE=$(grep -n "title" $GRUBMENU | awk -F ':' -v NUM=$NEXT_ENTRY '{ if (NR == NUM) {print $1}}')
    if [ "$LE" == "" ]
    then
        local DEF_ENTRY=$(awk -v N1=$LB '{if (NR>N1) {print}}' $GRUBMENU)
    else
        local DEF_ENTRY=$(awk -v N1=$LB -v N2=$LE '{if (NR>N1 && NR<N2) {print}}' $GRUBMENU)
    fi

    # get default kernel location
    DEFKNLPART=$(echo $DEF_ENTRY | \
                 grep -E "[^#]*(root|kernel).*\(hd[0-9]{1,2},[0-9]{1,2}\).*" | \
                 sed -e 's/.*\((hd[0-9]\+,[0-9]\+)\).*$/\1/')
}

get_grub_default_kernel_partition
echo $DEFKNLPART
